<?php
	class HandHistory extends AppModel{
		var $name = 'HandHistory';
		var $useTable = false;
		var $debugMode = 0;
		var $historyFolder = './userfiles';
		var $userName = '';
		var $handDate = '';
		var $tableName = '';
		var $findStrings = array();
		var $filePath = '';
		var $fileMD5 = '';
		var $tableStats = '';
		var $cacheVersion = '0.7';
		
		function getCacheVersion(){
			return $this->cacheVersion;
		}
		
		function calculateTableCssClass($handLog){
		//if it's a cash table roi > 0?
		$eventClass = ($handLog['tableStats']['roi'] < 0 ) ? 'lost' : 'won';
		//if its a STT how many players started
		//print_r($handLog['tableStats']);
		if(!empty($handLog['tableStats']['sttPosition'])){
			//how many runners?
			$runners = array_shift($handLog['hands']);
			//print_r($runners);
			$players = count($runners['Players']);
			$payoutPosition = 3;
			if($players <= 6){
				$payoutPosition = 2;
			}
			//was it a winner takes all?
			$eventClass = ($handLog['tableStats']['sttPosition'] <= $payoutPosition ) ? 'won' : 'lost';
			
		}
		return $eventClass;
		}

		function getFilePath()
		{
			$filePath = array($this->historyFolder,$this->userName,$this->handDate,$this->tableName);
			$this->filePath = implode('/',$filePath);
			return $this->filePath;
		}
		
		function setFileMD5($filePath){
			$this->fileMD5 = md5_file($filePath);
			return $this->fileMD5;
		}
		
		function fileFormat(){
			$this->findStrings = array(
				'tableName'=> array('expression'=>'^Table #([0-9]+) - (.*)'),
				'handNumber'=> array('expression'=>'^Starting Hand #([0-9]+)'),
				'gameType'=> array('expression'=>'^Game Type: ([.]+)'),
				'limitType'=> array('expression'=>'Limit Type: ([ A-Za-z]+)'),
				'tableType'=> array('expression'=>'Table Type: ([ A-Za-z]+)'),
				'moneyType'=> array('expression'=>'Money Type: ([ A-Za-z]+)'),
				'blindLevel' => array('expression'=>'Blinds are now (.[(\.,0-9)]+)/(.[\.,0-9]+)'),
				'button' => array('expression'=>'^Moving Button to seat ([0-9]+)'),
				'player' => array('expression'=>'Seat ([0-9]+): ([0-9a-zA-Z]+) - .([\.,0-9]+)'),
				'blindPosted'=> array('expression'=>'^([^ ]+) posts (small|big) blind \(.([\.,0-9]+)\)( \(all-in\))?'),
				'postdead'=> array('expression'=>'^([^ ]+) posts .([\.,0-9]+)( \(all-in\))?'),
				'yourHand'=> array('expression'=>'^Dealing \[(.+)\] to ([a-zA-Z0-9]+)'),
				'street'=> array('expression'=>'^Dealing ([A-Za-z]+) \[(.+)\]'),
				'check'=>array('expression'=>'^([^ ]+) checks'),
				'bet'=>array('expression'=>'^([^ ]+) (bets|raises to) .([\.,0-9]+)( \(all-in\))?'),
				'fold'=>array('expression'=>'^([^ ]+) folds'),
				'call'=>array('expression'=>'^([^ ]+) calls .([\.,0-9]+)'),
				'showdown'=>array('expression'=>'^([^ ]+)( folds and)? shows \[(.+)\]'),
				'muck'=>array('expression'=>'^([^ ]+) mucks'),
				'rake'=>array('expression'=>'^Taking Rake of .([\.,0-9]+)'),
				'split'=>array('expression'=>'^([^ ]+) ties([^#]*\#?[0-9]*), and wins .([\.,0-9]+) with: ([a-zA-Z :,0-9]*)'),
				'pot'=>array('expression'=>'^([^ ]+) wins .([\.,0-9]+) ?([^\#]+\#[0-9])?[^:]*:? ?([a-zA-Z :,0-9]*)'),
				'graceShow'=>array('expression'=>'^([^ ]+) has ([^jb][a-zA-Z :,0-9]*)'),
				'antes'=>array('expression'=>'^([^ ]+) posts ante of .([\.,0-9]+)( \(all-in\))?'),
				'endHand'=>array('expression'=>'^End Of Hand #([0-9]+)'),
			);
			while($line = fgets($this->historyFile)){
		
				foreach($this->findStrings as $key=>$expression){
					//debug( $expression['expression'] );
					if(eregi($expression['expression'],$line,$substrings)){
						
						$this->matchCallBack($key,$substrings);
					}
				}
		
			}

		}
		
		function matchCallBack($matchType,$substrings){
			Configure::Write('debug',0);
			switch($matchType){
				case 'tableName':
					$this->currentTable = $substrings[2];
				break;
				case 'blindLevel':
					$this->hands[$this->handNumber]['smallBet'] = $substrings[1];
					$this->hands[$this->handNumber]['bigBet'] = $substrings[2];
				break;
				case 'handNumber':
					$this->currentStreet = 'Pre Flop';
					$this->handNumber =$substrings[1];
				break;
				case 'split':
				
					//echo 'Found Split Pot '.$this->handNumber.'<br/>';
					//print_r($substrings); echo '<br/>';
					$this->hands[$this->handNumber]['pot']['Split'][] = array('player'=>$substrings[1],
																			 'value'=>$substrings[2],
																			 'potHand'=>$substrings[3]
																		);
				break;
				case 'pot':
					//echo '<p>'.$this->handNumber.' pot </p>';
					//print_r($substrings);
					if(!isset($this->hands[$this->handNumber]['pot'])){
						$this->hands[$this->handNumber]['pot'] = array('MainPot'=>array('potHand'=>''));
					}
					
					$potName = ($substrings[3]=='') ? 'MainPot' : str_replace(' ','',$substrings[3]);
					$potHand = ($substrings[4]=='') ? $this->hands[$this->handNumber]['pot']['MainPot']['potHand'] : $substrings[4];
					
					$this->hands[$this->handNumber]['pot'][$potName] = array('player'=>$substrings[1],
																			 'value'=>$substrings[2],
																			 'potHand'=>$potHand
																		);
				break;
				case 'graceShow':
					
					$this->hands[$this->handNumber]['pot']['MainPot']['potHand']=$substrings[2];
																		
				break;
				case 'player':
					if(!isset($this->hands[$this->handNumber]['Players'][$substrings[2]] )){
					$this->hands[$this->handNumber]['Players'][$substrings[2]] = array(
																'position'=>$substrings[1],
																'name'=>$substrings[2],
																'startingStack'=>$substrings[3]
																				);
					}
					else{
					$this->hands[$this->handNumber]['Players'][$substrings[2]]['endStack'] = $substrings[3];
					}
				break;
				case 'blindPosted':
					$this->hands[$this->handNumber]['blinds'][$substrings[2]]['player'] = $substrings[1];
					$this->hands[$this->handNumber]['blinds'][$substrings[2]]['value'] = $substrings[3];
					
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
																'player'=>$substrings[1],
																'action'=>$substrings[2],
																'value'=>$substrings[3],
																'all-in'=>$substrings[4]
																	);
				break;
				case 'postdead':
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
																'player'=>$substrings[1],
																'action'=>'post',
																'value'=>$substrings[2],
																'all-in'=>$substrings[4]
																	);
				break;
				case 'antes':
					$this->hands[$this->handNumber]['antes'] = $substrings[2];
					
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
																'player'=>$substrings[1],
																'action'=>'ante',
																'value'=>$substrings[2],
																'all-in'=>$substrings[3]
																	);
				break;
				case 'showdown':
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
								'player'=>$substrings[1],
								'action'=>'shows',
								'value'=>$substrings[3],
								'all-in'=>''
					);
					$this->hands[$this->handNumber]['Players'][$substrings[1]]['cards'] = $substrings[3];
					$this->hands[$this->handNumber]['Players'][$substrings[1]]['showdown'] = 1;
				break;
				case 'mucks':
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
								'player'=>$substrings[1],
								'action'=>'mucks',
								'value'=>'',
								'all-in'=>''
					);
					$this->hands[$this->handNumber]['Players'][$substrings[1]]['showdown'] = 1;
				break;
				case 'yourHand':
					$this->hands[$this->handNumber]['Players'][$substrings[2]]['cards'] = $substrings[1];
				break;
				case 'street':
					$this->hands[$this->handNumber]['streets'][$substrings[1]]['cards'] = $substrings[2];
					$this->currentStreet = $substrings[1];
				break;
				case 'check':
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
																					'player'=>$substrings[1],
																					'action'=>'check',
																					'value'=>''
																						);
				break;
				case 'bet':
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
																'player'=>$substrings[1],
																'action'=>'bet',
																'value'=>$substrings[3],
																'all-in'=>$substrings[4]
																	);
				break;
				case 'fold':
				
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
																'player'=>$substrings[1],
																'action'=>'fold',
																'value'=>''
																	);
				break;
				case 'call':
					$this->hands[$this->handNumber]['streets'][$this->currentStreet]['action'][] = array(
																'player'=>$substrings[1],
																'action'=>'call',
																'value'=>$substrings[2]
																	);				
				break;
				case 'rake':
					$this->hands[$this->handNumber]['pot']['rake'] = $substrings[1];
				break;
				
				case 'endHand':
					$this->handNumber = 'Invalid Hand After #'.$substrings[1];
				break;
				default: $this->hands[$this->handNumber][$matchType] = $substrings[1];
			}
		}
		
		function error($message){
			die($message);
		}
		
		function debug($debugValue){
			if($this->debugMode ==1){
				echo '<pre>';
					print_r($debugValue);
				echo '</pre>';
			}
		}
		
		function processHandFile(){
			$filePath = $this->getFilePath();
			
			$folderPath = explode('/',$filePath);
			array_pop($folderPath);
			$folderPath = implode('/',$folderPath);
			$md5string = md5_file($filePath);
			
			if(file_exists($folderPath.'.'.$md5string.'.txt')){
				debug('now here with cache file');
				$dataFormat = unserialize(file_get_contents($folderPath.'.'.$md5string.'.txt'));
				$this->hands = $dataFormat['hands'];
			}
			else{
				//debug('here withou cache file '.$filePath);
				$this->historyFile = @fopen($filePath,'r');
				if(!$this->historyFile) die("Failed to open history file $filePath");
				//debug('about to call file format');
				$this->fileFormat();
				//debug('STT?');
				if(strpos($this->currentTable,'STT')!==false){
					$this->sttFinishingPosition();
				}
				debug('about to get hand stats');
				$this->getHandStats();
				$this->serializeFileFormat($this->hands,$folderPath);
			}
		}
		function serializeFileFormat($handList,$folderPath){
			//echo 'here with '.$folderPath;
			$md5Data = $this->setFileMD5($this->filePath);
			$dataFormat = array(
								'version'=>$this->cacheVersion,
								'hands'=>$handList,
								'tableStats'=>$this->tableStats
								);
			//print_r($this->tableStats);
			$hash = serialize($dataFormat);
			file_put_contents($folderPath.'/.'.$md5Data.'.txt',$hash);
		}
		
		function printHandList(){
			foreach($this->hands as $handNumber=>$hand){
		//echo '<pre>'; print_r($hand); echo '</pre>';
			echo '<div class="hand" id="'.$handNumber.'">';
	
			$this->dealCards($handNumber,$hand);			
			$this->handStatus($handNumber,$hand);	
			$this->potSize($handNumber,$hand);			
			
			echo '</div>';//end hand div
	}
		}
		
		function dealCards($handNumber,&$hand){
			$cards = explode(' ',$hand['Players'][$this->userName]['cards']);
			$cardsIcon = '<div class="card value'.$cards[0].'"><p>'.$cards[0].'</p></div>';
			$cardsIcon2 = '<div class="card value'.$cards[1].'"><p>'.$cards[1].'</p></div>';
			echo $cardsIcon.' '.$cardsIcon2.'<br style="clear: both;"/>';
		}
		
		function handStatus($handNumber,&$hand){
			$hand['Players'][$this->userName]['startingStack'] = str_replace(',','',$hand['Players'][$this->userName]['startingStack']);
			$hand['Players'][$this->userName]['endStack'] = str_replace(',','',$hand['Players'][$this->userName]['endStack']);
	
			$won = (
				($hand['Players'][$this->userName]['endStack']+$hand['antes']
					-$hand['Players'][$this->userName]['startingStack']) >= 0 
			) ? 'Won' : 'Lost';
			$notCommitted = ( $hand['Players'][$this->userName]['startingStack']-$hand['antes']
				==
			$hand['Players'][$this->userName]['endStack'] );
	
			//don't treat undefended compulsory bets as a loss#
			$bigBlind = ($hand['blinds']['big']['player'] == $this->userName);
			$smallBlind = ($hand['blinds']['small']['player'] == $this->userName);
	
			$blinds = ($bigBlind) ? 'BigBlind' : $smallBlind;
	
			if($won=='Lost' && ($bigBlind || $smallBlind)){
				//did we bet?
				$loss =($hand['Players'][$this->userName]['endStack']+$hand['antes'] - $hand['Players'][$this->userName]['startingStack']);
				$loss = ($loss<0) ? $loss*-1 : $loss;
				//echo 'in the blinds loss is '.$loss;
	
				if(('$'.$loss == $hand['bigBet'] && $bigBlind)  || ('$'.$loss == $hand['smallBet'] && $smallBlind) ) $notCommitted = true;
			}
			
			$status = ($notCommitted) ? 'fold' : $won;	
			echo '<div class="handInfo"> #'.$handNumber.' '.$blinds.' '.$status.'</div>';
		}
		
		function potSize($handNumber,&$hand){
					//what's the pot size?
			$actionTotal = 0;
			foreach($hand['streets'] as $street=>$action){
			//print_r($action['action']);
			echo '<div class="'.str_replace(' ','',$street).'">';
			$streetCards = explode(' ',$action['cards']);
			echo '<div class="streetCards '.str_replace(' ','',$street).'Cards">';
				foreach($streetCards as $key=>$cards){
					if($cards) echo '<div class="card value'.$cards.'"><p>'.$cards.'</p></div>';
				}
				
			echo '</div>';
				if(is_array($action['action'] )){
					foreach($action['action'] as $key=>$value){
					$allin = ($value['all-in']) ? ' (all-in)' : '';
		echo '<div class="action '.$value['action'].'">'.$value['player'].' '.$value['action'].' '.$value['value'].$allin .'</div>';
							$actionTotal += $value['value'];
					}
				}
			echo '<br style="clear: both"/></div>';
			}//end of the streets
			
			echo '<div class="pot">';
		//print_r($hand['pot']);
			foreach($hand['pot'] as $potName=>$pot){
				$pot['potHand'] = ($pot['potHand']!='') ? $pot['potHand'] : $hand['Players'][$pot['player']]['cards'];
				echo '<p>'.$potName.' '.$pot['value'].'</p>';
				echo '<p>Winner: <span class="potWinner">'.$pot['player'].'</span></p>';
				echo '<p>Winning Hand: <span class="potWinningHand">'.$pot['potHand'].'</span></p>';
			}
			echo '</div>';
			
		}
		
		function getMyAction(){
		
		}
		
		function handAction(&$hand, $player, $street, $value){
			$hand['Players'][$player]['action'][$street] = $value;
		}
		
		function sttFinishingPosition(){
			$lastHand = array_keys($this->hands);
			$lastHand = array_pop($lastHand);
			$lastHand = $this->hands[$lastHand];

			if( count($lastHand['Players'])==2 
			&& $lastHand['Players'][$this->userName]['endStack'] != 0){
				$finishingPosition = 1;
			}
			else if($lastHand['Players'][$this->userName]['endStack']!=0){
				//sometimes you can win a tournament by knocking more than
				//one player out at a time - lotteries are like that
				//but sometimes you get disconnected
				$playersStillIn = array();
				foreach($lastHand['Players'] as $playerName=>$data){
					if($lastHand['Players'][$playerName]['endStack']!=0){
						$playersStillIn[] = $lastHand['Players'][$playerName];
					}
				}
				$finishingPosition = count($playersStillIn);
			}
			else{
				$finishingPosition = 10;
				foreach($this->hands as $handNumber=>$hand){
					//print_r( $hand['Players'][$this->userName] ); echo '<br/>';
					if(array_key_exists($this->userName,$hand['Players']) 
					&& $hand['Players'][$this->userName]['endStack'] == 0){
						$finishingPosition = count($hand['Players']);
					}
				}
			}
			//$this->debug( 'Finishing Position = '.$finishingPosition );
			$this->stt['finishingPosition'] = $finishingPosition;
			return $finishingPosition;
		}
		
		function statsForHand($hand){
								//players contirbutions to the pot
					if(!is_array($hand['streets'])) $hand['streets'] = array();
					foreach($hand['streets'] as $street=>$actionList){
						//every bet or call is a total 
						//contribution including the blinds
						
						//except for those bets that don't get called :(
						
																		
						//print_r($actionList); echo '<hr/>actionlist<hr/>';
						if(isset($actionList['action']) && is_array($actionList['action'])){
							foreach($actionList['action'] as $actionkey=>$action){
								
								
									//need to allow for unraised and undefended blinds 
									//as well as stealing the blinds
									//open raise is a call of the big blind (0.04) plus an extra amount on top
									//so if the blind is 4 and I bet 12 small folds big blind folds I win a post of 10 (my 4 to call + 2 + 4)
									
									//if I am small blind and it is raised in front when I fold my loss is .02
									
									//if I am small blind and it is raised in front my call is 8 but my action is another 6
									
									//if I three bet and win the pot from villains fold my total contribution is 
									//the value of the second bet
									
							//print_r($street); echo '<hr/>';
								if($action['action']=='small'){
										$watingForCall = array('player'=>$action['player'],
										'street'=>$street,
										'value'=>$action['value']);		
								}
								
								if($action['action']=='bet' 
										   || $action['action']=='big' 
										   || $action['action']=='post'
								){
									if($action['action']!='big' && $street=='Pre Flop'){ 
										$hand['Players'][$action['player']]['vpp']=1;
										$hand['Players'][$action['player']]['pfr']=1;
									}
									//AF = (Raise % + Bet %) / Call % 
									if($watingForCall){ 
										//this is a raise
										if($street!='Pre Flop'){
											if(!isset($hand['Players'][$action['player']]['raise'])){
												$hand['Players'][$action['player']]['raise'] = 0;
											}
											$hand['Players'][$action['player']]['raise']++;
										}
										
													$this->handAction($hand,
															$watingForCall['player'],
															$watingForCall['street'],
															$watingForCall['value']
															);
										//a bet is a call and a raise
										$this->handAction($hand,$action['player'], $street, $watingForCall['value']);
									}
									else{
										//initial bet
										if(!isset($hand['Players'][$action['player']]['bet'])){
											$hand['Players'][$action['player']]['bet'] = '';
										}
										$hand['Players'][$action['player']]['bet']++;
									}
									$watingForCall = array('player'=>$action['player'],
													'street'=>$street,
													'value'=>$action['value']);								
								}
								
								if($action['action']=='call'){
									//all in call might not be enough to cover the be
								
									if($street=='Pre Flop'){
										$hand['Players'][$action['player']]['vpp']=1;
									}
									else{											
										//postflop Calling
										if(!isset($hand['Players'][$action['player']]['call'])){
											$hand['Players'][$action['player']]['call']=0;
										}
										$hand['Players'][$action['player']]['call']++;
									}
									if($watingForCall){ 
										if($action['value'] != $watingForCall['value']) $watingForCall['value'] = $action['value'];
										//echo 'Call'; print_r($watingForCall); echo '<hr/>';

															$this->handAction($hand,
															$watingForCall['player'],
															$watingForCall['street'],
															$watingForCall['value']
															);
									}
									$this->handAction($hand,$action['player'], $street, $action['value']);
									$watingForCall = false;
								}
							}
						}
						//echo '<pre>'; print_r($hand['Players'][$this->userName]);echo '</pre>';
					}
					
					$profitKey = ($hand['pot']['MainPot']['player']==$this->userName) ? 'won' : 'lost';
					if(!isset($hand['Players'][$this->userName]['action']['won'])){
						$hand['Players'][$this->userName]['action']['won'] = 0;
					}
					if(!isset($hand['Players'][$this->userName]['action']['lost'])){
						$hand['Players'][$this->userName]['action']['lost'] = 0;
					}
					//profit / loss not = total pot
					if(isset($hand['Players'][$this->userName]['action']) &&
					   is_array($hand['Players'][$this->userName]['action'])){
						foreach($hand['Players'][$this->userName]['action'] as $street=>$action){		
							$hand['Players'][$this->userName]['action'][$profitKey] += $action;
						}
					}
					
					//blinds
					if(!is_array($hand['streets']['Pre Flop'])) $hand['streets']['Pre Flop'] = array();
					foreach($hand['streets']['Pre Flop'] as $actionList){
						foreach($actionList as $key=>$action){
							if($action['player']==$this->userName && $action['action']=='small'){
								$smallBlind=$action['value'];
							}
							if($action['player']==$this->userName && $action['action']=='big'){
								$bigBlind=$action['value'];
							}
						}
					}
					
					//running total 
					//print_r($hand['Players'][$this->userName]['action']); echo '<hr/>';
					if(!isset($hand['Players'][$this->userName]['action'])){
						$hand['Players'][$this->userName]['action'] = array('won'=>0,'lost'=>0);
					}
					$totalAction  = (
									 $hand['Players'][$this->userName]['action']['won']
									 + $hand['Players'][$this->userName]['action']['lost']
									//need to allow for unraised and undefended blinds 
									//as well as stealing the blinds
									//open raise is a call of the big blind (0.04) plus an extra amount on top
									//so if the blind is 4 and I bet 12 small folds big blind folds I win a post of 10 (my 4 to call + 2 + 4)
									);
									
				//assume we lost
				(float)$potTotal = 0;
				//handle split pots in case there are side pots
				if(!is_array($hand['pot'])) $hand['pot']=array();
				foreach($hand['pot'] as $sidePot=>$pot){
					//echo "<hr/> $sidePot";
						//print_r($pot);
						if ($pot['player']==$this->userName){
							$potTotal+=(float)$pot['value'];
						}
				}
				//echo "pot total = $potTotal action = $totalAction";
					//	echo '<hr/>';

				//pkr deduct the rake from the reported pot total
				//smaller side pots you do take down are already calculated as negative profit
				$handProfit =  ($totalAction <0) ? ($potTotal + $totalAction) : ($potTotal - $totalAction);

				//if you didn't win invert the profit to a loss
				//picking up a smaller side pot doesn't count as a win!
				
				$handProfit = ($potTotal > 0 || $handProfit < 0) 
				?  $handProfit 
				: $handProfit * -1;
								
				//if($handProfit == 0){$profitKey = "uncontested"; $uncontested['hands']++;}
				//debug( "$handNumber totalAction = $totalAction potTotal = $potTotal Profit is $handProfit <br/>" );

				//$runningTotal[$this->userName] += $handProfit;
				
				//debug ("$handNumber $totalAction {$runningTotal[$this->userName]} $profitKey<br/>");
				if(!isset($smallBlind)){$smallBlind=0;}
				if(!isset($bigBlind)){$bigBlind=0;}
				if(!isset($hand['Players'][$this->userName]['vpp'])){$hand['Players'][$this->userName]['vpp']=0;}
				if(!isset($hand['Players'][$this->userName]['pfr'])){$hand['Players'][$this->userName]['pfr']=0;}	
				if(!isset($hand['Players'][$this->userName]['call'])){$hand['Players'][$this->userName]['call']=0;}
				if(!isset($hand['Players'][$this->userName]['bet'])){$hand['Players'][$this->userName]['bet']=0;}
				if(!isset($hand['Players'][$this->userName]['raise'])){$hand['Players'][$this->userName]['raise']=0;}
				if(!isset($hand['Players'][$this->userName]['showdown'])){$hand['Players'][$this->userName]['showdown']=0;}
				
				
				return array('handProfit'=>$handProfit,
							 'totalAction'=>$totalAction,
							 'smallBlind'=>$smallBlind,
							 'bigBlind'=>$bigBlind,
							 'allPlayers'=>$hand['Players'],
							 'vpp'=>$hand['Players'][$this->userName]['vpp'],
							 'pfr'=>$hand['Players'][$this->userName]['pfr'],
							 'call'=>$hand['Players'][$this->userName]['call'],
							 'bet'=>$hand['Players'][$this->userName]['bet'],
							 'raise'=>$hand['Players'][$this->userName]['raise'],
							 'showdown'=>$hand['Players'][$this->userName]['showdown']
							 );
		}
		
		function getHandStats(){
			//echo '<pre>';
				$won = array('hands'=>0,'total'=>0);
				$lost = array('hands'=>0,'total'=>0);
				$uncontested = array('hands'=>0,'total'=>0);
				$smallBlind = array('hands'=>0,'total'=>0);
				$bigBlind = array('hands'=>0,'total'=>0);
				$button = array('hands'=>0,'total'=>0);
				//print_r($this->hands); die();
				$handsSeen = 0;
				$runningAction[$this->userName] = 0;
				$runningTotal[$this->userName] = 0;
				$vpp = 0; $pfr = 0; $call = 0; $bet = 0; $raise = 0;
				$wtsd = 0; $wtsdw = 0; $handProfit = 0; $profit = 0;
				foreach($this->hands as $handNumber=>$hand){
					$totals = $this->statsForHand($hand);
					$handsSeen++;
					//echo 'pre'; print_r($totals); echo '</pre>';
					$runningAction[$this->userName] += $totals['totalAction'];
					$runningTotal[$this->userName] += $totals['handProfit'];
					$vpp += (isset($totals['vpp'])) ? $totals['vpp'] : 0;
					$pfr += (isset($totals['vpp'])) ? $totals['pfr'] : 0;
					$call += (isset($totals['vpp'])) ? $totals['call'] : 0;
					$bet += (isset($totals['vpp'])) ? $totals['bet'] : 0;
					$raise += (isset($totals['vpp'])) ? $totals['raise'] : 0;
					
					$wtsd += (isset($totals['vpp'])) ? $totals['showdown'] : 0;
					$wtsdw += ($totals['handProfit'] >0 && $totals['showdown']) ? 1 : 0;
					
					$handProfit = $totals['handProfit'];
					$profit += $handProfit;
					if($handProfit > 0){ $won['hands']++; $won['total']+=$handProfit;}
					if($handProfit < 0 && $handProfit!=($totals['bigBlind']*-1)){ $lost['hands']++; $lost['total']+=$handProfit;}
					if($totals['smallBlind']){
						$smallBlind ['hands']++;
						$smallBlind ['total']+=$totals['smallBlind'];
					}
					if($totals['bigBlind']){
						$bigBlind ['hands']++;
						$bigBlind ['total']+=$totals['bigBlind'];
					}
				}//end hand loop
				
				
				$totals = array(
					'hands'=>$won['hands']+$lost['hands'],
					'total'=>$runningTotal[$this->userName]
				);

				
				$returnOnInvestment = $profit;
				
				//$this->debug($this->hands);
				//echo $this->currentTable;
								
				//print_r($runningTotal[$this->userName]);
				$roi = ($returnOnInvestment/$runningAction[$this->userName])*100;
				//echo '<p>&nbsp;</p>';
				
				$this->tableStats = array(
							'handsSeen'=>$handsSeen,
							'played'=>$totals['hands'],
							'won'=>$won['hands'],
							'lost'=>$lost['hands'],
							'bigBlind'=>$bigBlind['hands'],
							'smallBlind'=>$smallBlind['hands'],
							'totalAction'=>$runningAction[$this->userName],
							'totalWon'=>$won['total'],
							'totalLost'=>($lost['total']*-1),
							'totalBigBlnd'=>$bigBlind['total'],
							'totalSmallBlind'=>$smallBlind['total'],
							'roi'=>$returnOnInvestment,
							'roiPercent'=>$roi,
							'vpp'=>$vpp,
							'pfr'=>$pfr,
							'agression'=>array('call'=>$call,'bet'=>$bet,'raise'=>$raise),
							'wtsd'=>$wtsd,
							'wtsdw'=>$wtsdw,
							'sttPosition'=>'',
				);
				if(isset($this->stt) && !empty($this->stt)){
			$this->debug( '<div>debug Single Table Tournament Finishing Position = '.$this->stt['finishingPosition'].'</div>' );
					$this->tableStats['sttPosition'] = $this->stt['finishingPosition'];
				}
				$this->debug( "<div class=\"stats played\">Played: {$totals['hands']} Won: {$won['hands']} Lost: {$lost['hands']} BB: {$bigBlind['hands']} SB: {$smallBlind['hands']}</div>" );
				$this->debug( "<div class=\"stats value\">Total Action: {$runningAction[$this->userName]} Won: {$won['total']} Lost: ".($lost['total']*-1)." BB: {$bigBlind['total']} SB: {$smallBlind['total']} Return: $returnOnInvestment (".number_format($roi)."%)</div>");
				
			//echo '</pre>';
		}
		
	}
?>